﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NRemedy;
using NRemedy.Linq;
using System.Configuration;
using ARNative;
using NRemedy.MVC.UI;
using System.Text;
using System.Reflection;
namespace RemedyMVC.Controllers
{
    public class IncidentController : SessionController
    {
        //
        // GET: /Incident/
        protected static string ARServer = ConfigurationManager.AppSettings["ARServer"];
        protected static string ARUid = ConfigurationManager.AppSettings["ARUser"];
        protected static string ARPwd = ConfigurationManager.AppSettings["ARPwd"];
        static ARLoginContext login = null;


        //permission for control
        public PermissionControlObject<WS_Incident> p1;
        public PermissionControlObject<WS_Incident> p2;
        public PermissionControlObject<WS_Incident> p3;
        public PermissionControlObject<WS_Incident> p4;
        public PermissionControlObject<WS_Incident> p5;
        public PermissionControlObject<WS_Incident> p6;
        public PermissionControlObject<WS_Incident> p7;
        public PermissionControlObject<WS_Incident> p8;
        //permission for input
        public PermissionInputObject<WS_Incident> status1;
        public PermissionInputObject<WS_Incident> status2;
        public PermissionInputObject<WS_Incident> status3;
        public PermissionInputObject<WS_Incident> status4;

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (p1 == null) p1 = new PermissionControlObject<WS_Incident>(
                     incident => (incident.IncidentStatus == "已记录" && ARUserSession.GroupList.Contains("Incident Master")) ? ControlDisplayStatus.Normal : ControlDisplayStatus.Hidden
                 );

            if (p2 == null) p2 = new PermissionControlObject<WS_Incident>(
                     incident => (incident.IncidentStatus == "已分派" && (ARUserSession.GroupList.Contains("Incident Master")
                         || incident.Owner == ARUserSession.ARContext.User)
                         ) ? ControlDisplayStatus.Normal : ControlDisplayStatus.Hidden
                 );

            if (p3 == null) p3 = new PermissionControlObject<WS_Incident>(
                     incident => (incident.IncidentStatus == "处理中" && (ARUserSession.GroupList.Contains("Incident Master")
                         || incident.Owner == ARUserSession.ARContext.User)
                         ) ? ControlDisplayStatus.Normal : ControlDisplayStatus.Hidden
                 );

            if (p4 == null) p4 = new PermissionControlObject<WS_Incident>(
                     incident => (incident.IncidentStatus == "暂停中" &&
                         IsLeader(ARUserSession.ARContext.User, incident.OwnerTeam)
                         ) ? ControlDisplayStatus.Normal : ControlDisplayStatus.Hidden
                 );
            if (p5 == null) p5 = new PermissionControlObject<WS_Incident>(
                     incident => (incident.IncidentStatus == "已解决" && (ARUserSession.GroupList.Contains("Incident Master"))) ? ControlDisplayStatus.Normal : ControlDisplayStatus.Hidden
                 );
            if (p6 == null) p6 = new PermissionControlObject<WS_Incident>(
                           incident => (incident.IncidentStatus == "已重开" && ARUserSession.GroupList.Contains("Incident Master")) ? ControlDisplayStatus.Normal : ControlDisplayStatus.Hidden
                       );

            //根据赋值团队和负责人查询此人是否是领导

            //支持组领导可以暂停和取消暂停事件
            if (p7 == null) p7 = new PermissionControlObject<WS_Incident>(
                     incident => (incident.IncidentStatus == "处理中" && IsLeader(ARUserSession.ARContext.User, incident.OwnerTeam)
                         ) ? ControlDisplayStatus.Normal : ControlDisplayStatus.Hidden
                 );

            if (status1 == null) status1 = new PermissionInputObject<WS_Incident>(
                    //基本信息只能由服务台改变，不能是已关闭状态
                    incident => ((incident.IncidentStatus != "已关闭") && ARUserSession.GroupList.Contains("Incident Master"))
                        ? InputDisplayStatus.Normal : InputDisplayStatus.Disabled
                 );

            if (status2 == null) status2 = new PermissionInputObject<WS_Incident>(
                    //支持人员只能在已分派和处理中修改处理人员字段或者服务台可以修改
                     incident => (((incident.IncidentStatus == "已分派" || (incident.IncidentStatus == "处理中")
                         && incident.Owner == ARUserSession.ARContext.User)) ||
                         (incident.IncidentStatus != "已关闭") && ARUserSession.GroupList.Contains("Incident Master"))
                         ? InputDisplayStatus.Normal : InputDisplayStatus.Disabled
                  );
            //if (status3 == null) status3 = new PermissionInputObject<WS_Incident>(
            //        //只有在评审中时才能选择关闭类型
            //       incident => ((incident.IncidentStatus == "评审中") && ARUserSession.GroupList.Contains("问题管理经理"))
            //           ? InputDisplayStatus.Normal : InputDisplayStatus.Disabled
            //    );
            //if (status4 == null) status4 = new PermissionInputObject<WS_Incident>(
            //        //关闭或权益措施后，都不能修改
            //       incident => (incident.IncidentStatus == "已关闭" || incident.IncidentStatus == "已取消")
            //           ? InputDisplayStatus.Disabled : InputDisplayStatus.Normal
            //    );
        }

        public ActionResult Index(String requestid)
        {
            return View();
        }

        [HttpGet]
        public string GetDuration(string Category, string SubCategory)
        {
            //根据事件大类、小类,获取处理时长
            WS_INCCategoryItem c = null;
            string duration = "";
            using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
            {
                var q = from i in new ARSet<WS_INCCategoryItem>(context)
                        where i.CTRIP_Category == Category && i.CTRIP_SubCategory == SubCategory
                        select i;
                c = q.ToList().FirstOrDefault();
            }
            duration = c.CTRIP_CHRTreatmentDuration;
            return duration;
        }


        #region 1.0根据输入的字获取相应的名字列表
        [HttpGet]
        public ActionResult GetNameListByName(string term)
        {
            string Name = term;
            //string NameList = "";
            IList<WS_People> peopleList = null;
            using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
            {
                ARProxy<WS_People> proxy = new ARProxy<WS_People>(context);
                string qualification = string.Format("\'536870937\' like \"%{0}%\"", Name);
                TotalMatch t = new TotalMatch();
                List<uint> fields = new List<uint>();
                fields.Add(536870937u);    //姓名
                peopleList = proxy.GetEntryList(qualification, fields, 0, null, t, null);
            }
            //if (peopleList != null)
            //{
            //    foreach (var people in peopleList)
            //    {
            //        NameList += string.Format("{0},", people.FullName);
            //    }
            //    NameList = NameList.TrimEnd(',');
            //}
            IList<object> nameCollection = new List<object>();
            if (peopleList != null)
            {
                foreach (var people in peopleList)
                {
                    nameCollection.Add(new { label = people.FullName, value = people.FullName });
                }
            }
            return Json(nameCollection, JsonRequestBehavior.AllowGet);
        }

        #endregion


        #region 2.0根据姓名获取此人的相关信息
        [HttpGet]
        public JsonResult GetPeopleInfoByName(string Name)
        {
            WS_People people = new WS_People();
            IList<WS_People> peopleList = null;
            using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
            {
                ARProxy<WS_People> proxy = new ARProxy<WS_People>(context);
                string qualification = string.Format("\'536870937\' = \"{0}\"", Name);
                TotalMatch t = new TotalMatch();
                //t.Value = -1;
                List<uint> fields = new List<uint>();
                fields.Add(536870937u);    //姓名
                fields.Add(536870915u);   //用户工号
                fields.Add(536870920u);    //电话
                fields.Add(536870950u);    //EMail
                fields.Add(536870934u);   //分公司
                fields.Add(536870929u);  //地点
                fields.Add(536870928u);  //部门
                fields.Add(536870927u);  //座位
                peopleList = proxy.GetEntryList(qualification, fields, 0, null, t, null);
            }
            if (peopleList != null && peopleList.Count > 0)
            {
                people = peopleList[0];
            }
            return Json(people, JsonRequestBehavior.AllowGet);
        }



        #endregion


        #region 我新加的方法

        /// <summary>
        /// 判定是否是领导
        /// </summary>
        /// <param name="user"></param>
        /// <param name="groupname"></param>
        /// <returns></returns>
        [NonAction]
        public bool IsLeader(string user, string groupname)
        {
            bool IsLeader = false;
            using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
            {
                try
                {
                    var q = from i in new ARSet<WS_TeamMember>(context)
                            where i.Memeber == user && i.Team == groupname
                            select i.TeamLeader;
                    foreach (var m in q)
                    {
                        if (m != null && m.ToString() == "Yes")
                            return true;
                    }
                }
                catch (Exception e)
                {


                }
            }

            return IsLeader;
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteIncident(String requestid)
        {

            using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
            {
                ARProxy<WS_Incident> proxy = new ARProxy<WS_Incident>(context);
                proxy.DeleteEntry(new WS_Incident { RequestID = requestid });
            }
            return Json(new { });

        }

        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult GetIncidentInfo(String queryParams, string sort, string order)
        //{

        //    //List<ARSortInfo> sortInfo = null;
        //    //if (sort != null && order != null)
        //    //{
        //    //    ARSortInfo si = new ARSortInfo();
        //    //    DefaultModelMetaProvider Provider = new DefaultModelMetaProvider();
        //    //    ARFieldMetaData md = Provider.GetARFieldAttOnProperty(typeof(WS_Incident), sort);
        //    //    if (order == "desc")
        //    //        si.Order = SortOrder.SORT_DESCENDING;
        //    //    else
        //    //        si.Order = SortOrder.SORT_ASCENDING;
        //    //    if (md != null)
        //    //    {
        //    //        si.FieldId = md.DatabaseID;
        //    //        sortInfo = new List<ARSortInfo>();
        //    //        sortInfo.Add(si);
        //    //    }

        //    //}
        //    //IList<object> incidentlit = new List<object>();
        //    //using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
        //    //{
        //    //    ARProxy<WS_Incident> proxy = new ARProxy<WS_Incident>(context);
        //    //    int total = 0;
        //    //    List<uint> fieldids = new List<uint> { 1, 536870922, 536870914, 536870924, 536870955, 536870956, 536870937, 536870916 };
        //    //    foreach (var o in proxy.GetEntryList(null, fieldids, null, null, ref total, sortInfo))
        //    //    {

        //    //        incidentlit.Add(new
        //    //        {
        //    //            RequestID = o.RequestID,
        //    //            IncidentNumber = o.IncidentNumber,
        //    //            Status2 = o.Status2,
        //    //            Subject = o.Subject,
        //    //            OwnerTeam = o.OwnerTeam,
        //    //            Owner = o.Owner,
        //    //            FullName = o.FullName,
        //    //            Symptom = o.Symptom
        //    //        });

        //    //    }

        //    //}
        //    //List<object> test = new List<object>();

        //    //if (queryParams == "待分配事件")
        //    //{
        //    //    test.Add(incidentlit[0]);
        //    //    return Json(test);
        //    //}
        //    //if (queryParams == "未解决事件")
        //    //{
        //    //    test.Add(incidentlit[1]);
        //    //    return Json(test);
        //    //}
        //    //if (queryParams == "需回访事件")
        //    //{
        //    //    test.Add(incidentlit[2]);
        //    //    return Json(test);
        //    //}
        //    //return Json(incidentlit);
        //    return null;

        //}


        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult GetSearchCondition()
        //{
        //    IList<object> SearchList = new List<object>();
        //    IList<object> SearchList_Childeren = new List<object>();

        //    using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
        //    {
        //        var h = from i in new ARSet<WS_IncidentTopTab>(context)
        //                where i.CTRIP_FormName == "WS_Incident" 
        //                //&& i.CTRIP_UserRole == NRemedy.WS_IncidentTopTab.CTRIP_UserRole_Enum.ServiceDesk
        //                select i.CTRIP_IncidentTopOne;
        //        int n = 0;
        //        try
        //        {
        //            foreach (var m in h.ToList().Distinct().ToList())
        //            {
        //                n++;
        //                SearchList_Childeren.Add(new { id = "condition1_ID_" + n, text = m });
        //            }
        //        }
        //        catch (Exception e)
        //        {

        //            throw e;
        //        }

        //    }
        //    SearchList.Add(new { text = "搜索条件", children = SearchList_Childeren });
        //    return Json(SearchList);

        //}

        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult GetSearchCondition_combobox(string combobox_param)
        //{

        //    IList<object> SearchList = new List<object>();
        //    using (ARLoginContext context = new ARLoginContext(ARServer, ARUid, ARPwd))
        //    {
        //        var h = from i in new ARSet<WS_IncidentTopTab>(context)
        //                where i.CTRIP_IncidentTopOne == combobox_param && i.CTRIP_FormName == "WS_Incident"
        //                //&& i.CTRIP_UserRole == NRemedy.WS_IncidentTopTab.CTRIP_UserRole_Enum.ServiceDesk
        //                select i;
        //        WS_IncidentTopTab tab = null;
        //        for (int count = 0; count < h.Count<WS_IncidentTopTab>(); count++)
        //        {
        //            tab = h.ToList<WS_IncidentTopTab>()[count];
        //            if (count == 0)
        //            {
        //                SearchList.Add(new { desc = tab.CTRIP_IncidentQuery.ToARKeyWordDecoded(this), text = tab.CTRIP_IncidentTopTwo, id = "combobox_" + count, selected = true });
        //            }
        //            else
        //            {
        //                SearchList.Add(new { desc = tab.CTRIP_IncidentQuery.ToARKeyWordDecoded(this), text = tab.CTRIP_IncidentTopTwo, id = "combobox_" + count });
        //            }
        //        }

        //    }
        //    return Json(SearchList);

        //}

        #endregion

        [HttpGet]
        public ActionResult Form(string id)
        {
            var formModel = RouteData.Values[NRemedyUIExtension.FormModelKey];
            if (formModel != null && formModel.ToString() == "Detail")
            {
                return Detail(id);
            }
            else
            {
                return Create();
            }
        }

        [HttpPost]
        public ActionResult Form(WS_Incident incident, FormCollection collection, string id)
        {
            var formModel = RouteData.Values[NRemedyUIExtension.FormModelKey];
            if (formModel != null && formModel.ToString() == "Detail")
            {
                if (collection.AllKeys.Contains(NeedKeyAttribute.ARRequestID))
                {
                    //当点击保存按钮时状态不会改变
                    if (!string.IsNullOrEmpty(collection["buttonclick"]) && collection["buttonclick"] != Incident_Action.Logged)
                    {
                        //根据操作判定状态
                        incident.tmp_Action = collection["buttonclick"];
                        switch (incident.tmp_Action)
                        {
                            case Incident_Action.Assigned: incident.IncidentStatus = Incident_Satus_Name.Assigned; break;
                            case Incident_Action.Resolve: incident.IncidentStatus = Incident_Satus_Name.Resolved;
                                incident.ResolvedBy = ARUserSession.ARContext.User;
                                incident.ResolvedDate = DateTime.Now;
                                collection.Add("ResolvedBy", null);
                                collection.Add("ResolvedDate", null);
                                break;
                            case Incident_Action.Logged: incident.IncidentStatus = Incident_Satus_Name.Logged; break;
                            case Incident_Action.Accepted: incident.IncidentStatus = Incident_Satus_Name.Active; break;
                            case Incident_Action.ReAssigned: incident.IncidentStatus = Incident_Satus_Name.Logged; break;
                            case Incident_Action.Pending: incident.IncidentStatus = Incident_Satus_Name.Pending; break;
                            case Incident_Action.CancelPending: incident.IncidentStatus = Incident_Satus_Name.Active; break;
                            case Incident_Action.Closed: incident.IncidentStatus = Incident_Satus_Name.Closed;
                                incident.CloseBy = ARUserSession.ARContext.User;
                                incident.ClosedDateTime = DateTime.Now;
                                collection.Add("CloseBy", null);
                                collection.Add("ClosedDateTime", null);
                                break;
                            case Incident_Action.Reopened: incident.IncidentStatus = Incident_Satus_Name.Reopened; break;

                            default: break;

                        }
                        collection.Add("IncidentStatus", null);
                        collection.Add("tmp_Action", null);

                    }
                    //每次操作都更新修改时间和修改人(改为用filter实现)
                    //collection.Add("LastModBy", null);
                    //collection.Add("LastModDateTime", null);
                    //incident.LastModBy = ARUserSession.ARContext.User;
                    //incident.LastModDateTime = DateTime.Now;
                    return Detail(collection, id, incident);


                }
                else
                    throw new MemberAccessException(string.Format("{0} must be include in form request", NeedKeyAttribute.ARRequestID));
            }
            else
            {

                return Create(incident, collection);
            }
        }

        [NonAction]
        public ActionResult Create()
        {
            ViewData.Model = new WS_Incident();
            return View("Create");
        }

        [NonAction]
        public ActionResult Create(WS_Incident incident, FormCollection collection)
        {
            //创建的时候只能保存，分派，解决事件
            if (!string.IsNullOrEmpty(collection["buttonclick"]))
            {
                //根据操作判定状态
                incident.tmp_Action = collection["buttonclick"];
                switch (incident.tmp_Action)
                {
                    case Incident_Action.Logged: incident.IncidentStatus = Incident_Satus_Name.Logged; break;
                    case Incident_Action.Assigned: incident.IncidentStatus = Incident_Satus_Name.Assigned; break;
                    case Incident_Action.Resolve: incident.IncidentStatus = Incident_Satus_Name.Resolved;
                        incident.ResolvedBy = ARUserSession.ARContext.User;
                        incident.ResolvedDate = DateTime.Now;
                        break;
                    default: break;

                }
            }

            ARProxy<WS_Incident> proxy = new ARProxy<WS_Incident>(ARUserSession.ARContext);
            incident.CreatedBy = ARUserSession.ARContext.User;
            incident.CreatedDateTime = DateTime.Now;
            incident.LastModBy = ARUserSession.ARContext.User;
            incident.LastModDateTime = DateTime.Now;
            incident.ShortDescription = "事件";
            proxy.CreateEntry(incident);
            //proxy.CreateEntry(incident, delegate(PropertyInfo p)
            //{
            //    return !(p.Name == "CreatedBy" || p.Name == "RequestDate");
            //});
            return RedirectToAction("index");
        }

        [NonAction]
        public ActionResult Detail(string IncidentNumber)
        {

            if (string.IsNullOrEmpty(IncidentNumber))
            {
                throw new ArgumentNullException("IncidentNumber");
            }

            var q = from s in new ARSet<WS_Incident>(ARUserSession.ARContext)
                    where s.IncidentNumber == IncidentNumber
                    select s;

            ViewData.Model = q.ToList().First();

            return View("Detail");
        }

        [NonAction]
        public ActionResult Detail(FormCollection collection, string IncidentNumber, WS_Incident incident)
        {

            string requestid = collection[NeedKeyAttribute.ARRequestID];
            //the collection is propertyname
            ARProxy<WS_Incident> proxy = new ARProxy<WS_Incident>(ARUserSession.ARContext);
            var set = new ARSet<WS_Incident>(ARUserSession.ARContext);
            incident.RequestID = requestid;
            //不用更新RequestID
            if (collection.AllKeys.Contains("RequestID"))
            {
                collection.Remove("RequestID");
            }
            proxy.SetEntry(incident, delegate(ARBaseForm model, PropertyInfo pi)
            {
                return collection.AllKeys.Contains(pi.Name);
            });


            var q2 = from s in set
                     where s.RequestID == requestid
                     select s;

            ViewData.Model = q2.ToList().First();

            return View("Detail");
        }

        [HttpPost]
        public ActionResult Search(FormCollection collection)
        {
            StringBuilder sb = new StringBuilder("1=1");
            foreach (var c in collection.AllKeys)
            {
                sb.Append(" AND ");
                sb.Append("'")
                    .Append(c)
                    .Append("' LIKE \"%")
                    .Append(collection[c])
                    .Append("%\"");

            }

            ViewBag.Q = sb.ToString();

            return View();
        }


        public class Incident_Action
        {
            /// <summary>
            /// 记录事件
            /// </summary>
            public const string Logged = "记录事件";
            /// <summary>
            /// 保存事件
            /// </summary>
            public const string Save = "保存事件";
            /// <summary>
            /// 分派事件
            /// </summary>
            public const string Assigned = "分派事件";
            /// <summary>
            /// 接受事件
            /// </summary>
            public const string Accepted = "接受事件";
            /// <summary>
            /// 重分派事件
            /// </summary>
            public const string ReAssigned = "重分派事件";
            /// <summary>
            /// 处理事件
            /// </summary>
            public const string Active = "处理事件";
            /// <summary>
            /// 暂停事件
            /// </summary>
            public const string Pending = "暂停事件";
            /// <summary>
            /// 取消暂停事件
            /// </summary>
            public const string CancelPending = "取消暂停事件";
            /// <summary>
            /// 解决事件
            /// </summary>
            public const string Resolve = "解决事件";
            /// <summary>
            /// 关闭事件
            /// </summary>
            public const string Closed = "关闭事件";
            /// <summary>
            /// 邮件回访
            /// </summary>
            public const string MailTo = "邮件回访";
            /// <summary>
            /// 重开事件
            /// </summary>
            public const string Reopened = "重开事件";
        }

        public class Incident_Action_Name
        {
            public const string Save = "save";
            public const string Submit = "_submit";
            public const string Assigned = "Assigned";
            public const string Accepted = "Accepted";
            public const string ReAssigned = "ReAssigned";
            public const string Active = "Active";
            public const string Pending = "Pending";
            public const string Resolve = "Resolve";
            public const string Closed = "Closed";
            public const string MailTo = "MailTo";
            public const string Reopened = "Reopened";
            public const string FirstSave = "first_save";
            public const string FirstSubmit = "first_submit";
        }

        public class Incident_Satus_Name
        {
            ///<summary>
            /// 已记录
            /// </summary>
            public const string Logged = "已记录";

            ///<summary>
            /// 已分派
            /// </summary>
            public const string Assigned = "已分派";

            /// <summary>
            /// 处理中
            /// </summary>
            public const string Active = "处理中";

            /// <summary>
            /// 暂停中
            /// </summary>
            public const string Pending = "暂停中";

            /// <summary>
            /// 已解决
            /// </summary>
            public const string Resolved = "已解决";

            /// <summary>
            /// 已关闭
            /// </summary>
            public const string Closed = "已关闭";

            /// <summary>
            /// 已重开
            /// </summary>
            public const string Reopened = "已重开";

        }
    }

}
